package com.usoft.example.search;

import com.usoft.grpc.example.search.SearchServiceGrpc;
import io.grpc.Server;
import io.grpc.netty.NettyServerBuilder;
import java.util.logging.Logger;

/**
 * Created by xinxingegeya on 15/9/25.
 */
public class SearchServer {

    private static final Logger logger = Logger
        .getLogger(SearchServer.class.getName());

    /* The port on which the server should run */
    private int port = 8888;
    private Server server;

    private void start() throws Exception {
        server = NettyServerBuilder.forPort(port)
            .addService(SearchServiceGrpc.bindService(new SearchServiceImpl()))
            .build().start();
        logger.info("Server started, listening on " + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                // Use stderr here since the logger may have been reset by its JVM shutdown hook.
                System.err.println(
                    "*** shutting down gRPC server since JVM is shutting down");
                SearchServer.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    /**
     * Await termination on the main thread since the grpc library uses daemon
     * threads.
     */
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    /**
     * Main launches the server from the command line.
     */
    public static void main(String[] args) throws Exception {
        final SearchServer searchServer = new SearchServer();
        searchServer.start();
        searchServer.blockUntilShutdown();
    }
}
